﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_ORDER.BizLogic;
using ERP_RORZE_ORDER.Common;
using ERP_RORZE_ORDER.Common.ValueObject;
using ERP_RORZE_ORDER.OrderObject.Forms;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_SYSTEM;
using ERP_RORZE_TOOL.DBAccess;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_ORDER.OrderObject.UserControls
{
    public partial class ucOrderInput : DevExpress.XtraEditors.XtraUserControl
    {
        private int index = 0;
        public int _action = 1;
        DXPopupMenu menu;
        private bool filterExpired;
        OrderInputHelper helper = new OrderInputHelper(new OrderInput());

        private LogUtils log;
        #region Handle methods
        public ucOrderInput()
        {
            InitializeComponent();
            InitPopupMenu();

            log = new LogUtils();
            BindDatatoGrid();
            //gridView1.BestFitColumns();
            this.dropbtExport.DropDownControl = menu;
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            DeleteRows();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            EditRow();
        }

        private void btAddNew_Click(object sender, EventArgs e)
        {
            AddNew();
        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            BindDatatoGrid();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            ImportData();
        }

        private void gridView1_CustomDrawEmptyForeground(object sender, DevExpress.XtraGrid.Views.Base.CustomDrawEventArgs e)
        {
            if (gridView1.RowCount != 0)
                return;

            StringFormat drawFormat = new StringFormat();

            drawFormat.Alignment = drawFormat.LineAlignment = StringAlignment.Center;

            e.Graphics.DrawString("No items exist in this view", e.Appearance.Font, SystemBrushes.ControlDark, new RectangleF(e.Bounds.X, e.Bounds.Y, e.Bounds.Width, e.Bounds.Height), drawFormat);

        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            var gridView = (GridView)sender;
            var point = gridView.GridControl.PointToClient(Control.MousePosition);

            DoDoubleClick(gridView, point);
        }

        private void addNewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddNew();
        }

        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditRow();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DeleteRows();
        }

        private void gridControl1_ProcessGridKey(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeleteRows();
            }
        }

        private void btExpiredOrder_Click(object sender, EventArgs e)
        {
            if (!filterExpired)
            {
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    btExpiredOrder.Text = "All Orders";
                    filterExpired = true;
                    //gridView1.ActiveFilterString = "[ArrivedDate] is null AND [Deadline] <= '"+DateTime.Now.Date.ToShortDateString()+"'";

                    OrderInputHelper helper = new OrderInputHelper(new OrderInput());
                    gridControl1.DataSource = helper.GetAllExpired();
                    //gridView1.BestFitColumns();
                    Utilities.GridUtil.SelectRow(gridView1, index, _action);
                    Cursor.Current = Cursors.Default;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            else
            {
                Cursor.Current = Cursors.WaitCursor;
                btExpiredOrder.Text = "Expired Orders";
                filterExpired = false;
                BindDatatoGrid();
                Cursor.Current = Cursors.Default;

            }
        }

        #endregion

        #region Private methods
        public void BindDatatoGrid()
        {
            OrderInputHelper helper = new OrderInputHelper(new OrderInput());
            gridControl1.DataSource = helper.GetAll();
            //gridView1.BestFitColumns();
            Utilities.GridUtil.SelectRow(gridView1, index, _action);
        }

        private void DoDoubleClick(GridView v, Point p)
        {
            _action = 1;
            index = gridView1.FocusedRowHandle;
            var info = v.CalcHitInfo(p);
            if (info.InRow || info.InRowCell)
            {
                frm_OrderInputEdit fr = new frm_OrderInputEdit(this);
                if (!Utilities.FormUtil.IsFormOpen(fr))
                {
                    var row = new DataRow[gridView1.SelectedRowsCount];
                    row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

                    int productId = int.Parse(row[0][OrderConstants.Entities.OrderInput.FieldName.ID].ToString());
                    helper.ValueObject.ID = productId;
                    helper.LoadOne();

                    fr.ID = helper.ValueObject.ID;
                    fr.OrderID = helper.ValueObject.OrderID;
                    fr.ProductID = helper.ValueObject.ProductID;
                    fr.Deadline = helper.ValueObject.Deadline;
                    fr.Quantity = helper.ValueObject.Quantity;
                    fr.ExchangeRate = helper.ValueObject.ExchangeRate;
                    fr.Purchaser = helper.ValueObject.PurchaseID;
                    fr.PGroup = helper.ValueObject.PGroupID;
                    fr.Note = helper.ValueObject.Note;
                    fr.Status = helper.ValueObject.Status;
                    fr.ArrivedDate = helper.ValueObject.ArrivedDate;
                    fr.Price = helper.ValueObject.Price;

                    fr.StartPosition = FormStartPosition.CenterScreen;
                    fr.Show();
                }
            }
        }

        private void DeleteRows()
        {
            if (gridView1.SelectedRowsCount > 0)
            {
                var row = new DataRow[gridView1.SelectedRowsCount];
                var productId = new int[gridView1.SelectedRowsCount];

                for (int i = 0; i < gridView1.SelectedRowsCount; i++)
                {
                    row[i] = gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
                    productId[i] = int.Parse(row[i][OrderConstants.Entities.OrderInput.FieldName.ID].ToString());
                }


                if (MessageBox.Show(OrderConstants.Message.DeleteQuestion, OrderConstants.Form.MessageBox.Warning,
                                MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    OrderInputHelper helper = new OrderInputHelper(new OrderInput());
                    for (int i = 0; i < productId.Length; i++)
                    {
                        helper.ValueObject.ID = productId[i];
                        if (helper.Delete() > 0)
                        {

                            //write Log
                            log.Table = LogConstant.Table.F2Order.OrderInput;
                            log.Task = LogConstant.Task.Delete;
                            log.Description = "OrderID: " + row[i][OrderConstants.Entities.OrderInput.FieldName.OrderID] + "; ProductID: " + row[i][OrderConstants.Entities.OrderInput.FieldName.ProductID];
                            log.WriteLog();

                            _action = 2;
                        }
                        else
                        {
                            MessageBox.Show(OrderConstants.Message.DeleteFailed, OrderConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    BindDatatoGrid();


                }
            }
            else
            {
                MessageBox.Show(OrderConstants.Message.TableIsNull, OrderConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }

        private void EditRow()
        {

            if (gridView1.SelectedRowsCount > 0)
            {
                frm_OrderInputEdit fr = new frm_OrderInputEdit(this);
                if (!Utilities.FormUtil.IsFormOpen(fr))
                {


                    var row = new DataRow[gridView1.SelectedRowsCount];
                    row[0] = gridView1.GetDataRow(gridView1.GetSelectedRows()[0]);

                    index = gridView1.FocusedRowHandle;
                    _action = 1;

                    int productId = int.Parse(row[0][OrderConstants.Entities.OrderInput.FieldName.ID].ToString());
                    helper.ValueObject.ID = productId;
                    helper.LoadOne();

                    fr.ID = helper.ValueObject.ID;
                    fr.OrderID = helper.ValueObject.OrderID;
                    fr.ProductID = helper.ValueObject.ProductID;
                    fr.Deadline = helper.ValueObject.Deadline;
                    fr.Quantity = helper.ValueObject.Quantity;
                    fr.ExchangeRate = helper.ValueObject.ExchangeRate;
                    fr.Purchaser = helper.ValueObject.PurchaseID;
                    fr.PGroup = helper.ValueObject.PGroupID;
                    fr.Note = helper.ValueObject.Note;
                    fr.Status = helper.ValueObject.Status;
                    fr.ArrivedDate = helper.ValueObject.ArrivedDate;
                    fr.Price = helper.ValueObject.Price;

                    fr.StartPosition = FormStartPosition.CenterScreen;
                    fr.Show();
                }
            }
            else
            {
                MessageBox.Show(OrderConstants.Message.TableIsNull, OrderConstants.Form.MessageBox.Message, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }

        private void AddNew()
        {
            Cursor.Current = Cursors.WaitCursor;
            Form fr = new frm_OrderInputAdd(this);
            fr.StartPosition = FormStartPosition.CenterScreen;

            if (!Utilities.FormUtil.IsFormOpen(fr))
            {
                fr.Show();
            }
            else
            {
                //fr.WindowState = FormWindowState.Normal;

                //fr.BringToFront();
                //fr.TopMost = true;
                //fr.Activate();
            }

            Cursor.Current = Cursors.Default;

        }

        protected virtual void InitPopupMenu()
        {
            menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem("Export all", new EventHandler(OnItemClickExportAll), null, null, null, null));
            menu.Items.Add(new DXMenuItem("Export selected row(s)", new EventHandler(OnItemClickExportRows), null, null, null, null));

        }
        void OnItemClickExportAll(object sender, EventArgs e)
        {
            Utilities.ExportToExcel(gridView1, 1, true);
        }
        void OnItemClickExportRows(object sender, EventArgs e)
        {
            Utilities.ExportToExcel(gridView1, 0, true);
        }

        private void ImportData()
        {
            INISettings mySetting = new INISettings();
            SqlConnection myConnection = new SqlConnection(mySetting.SQLConnectionString);

            int countOk = 0;
            int countDup = 0;
            int countErr = 0;

            List<Utilities.ListItem> listDup = new List<Utilities.ListItem>();
            List<Utilities.ListItem> listErr = new List<Utilities.ListItem>();
            FileDialog importFile = new OpenFileDialog();
            importFile.Filter = "Excel 2007-2013|*.xlsx|Excel 97-2003 (*.xls)|*.xls";
            if (importFile.ShowDialog() == DialogResult.OK)
            {
                OleDbConnection excelConnection = null;
                try
                {
                    Control parent = progressPanel1.Parent;
                    progressPanel1.Location =
                        new Point(parent.Bounds.X + parent.Bounds.Width / 2 - progressPanel1.Width / 2,
                                  parent.Bounds.Y + parent.Bounds.Height / 2 - progressPanel1.Height / 2);
                    progressPanel1.Visible = true;
                    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                                                   importFile.FileName +
                                                   ";Extended Properties=Excel 12.0;Persist Security Info=False";
                    excelConnection = new OleDbConnection(excelConnectionString);
                    OleDbCommand cmd =
                        new OleDbCommand("select [OrderID],[ProductID],[Deadline],[Quantity],[ExchangeRate],[PurchaseID],[PGroupID]" +
                                         ",[Status],[Note],[ArrivedDate] from [Sheet1$]",
                            excelConnection);
                    excelConnection.Open();
                    OleDbDataReader dReader;
                    dReader = cmd.ExecuteReader();
                    int i = 0;
                    int line = 1;

                    string OrderID = string.Empty;
                    string ProductID = string.Empty;
                    string Deadline = string.Empty;
                    string Quantity = string.Empty;
                    string ExchangeRate = string.Empty;
                    string PurchaseID = string.Empty;
                    string PGroupID = string.Empty;
                    string Status = string.Empty;
                    string Note = string.Empty;
                    string ArrivedDate = string.Empty;
                    string Price = string.Empty;

                    myConnection.Open();
                    while (dReader.Read())
                    {
                        bool exist = false;
                        line++;

                        //check null
                        try
                        {
                            if (dReader["OrderID"].ToString().Trim().Equals(string.Empty)
                                && dReader["ProductID"].ToString().Trim().Equals(string.Empty)
                                && dReader["Deadline"].ToString().Trim().Equals(string.Empty)
                                && dReader["Quantity"].ToString().Trim().Equals(string.Empty)
                                && dReader["ExchangeRate"].ToString().Trim().Equals(string.Empty)
                                && dReader["PurchaseID"].ToString().Trim().Equals(string.Empty)
                                && dReader["PGroupID"].ToString().Trim().Equals(string.Empty)
                                && dReader["Status"].ToString().Trim().Equals(string.Empty)
                                && dReader["Note"].ToString().Trim().Equals(string.Empty)
                                && dReader["ArrivedDate"].ToString().Trim().Equals(string.Empty)
                                )
                            {
                                countErr++;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["OrderID"].ToString(), "Null line"));
                                exist = true;
                            }
                        }
                        catch (Exception e)
                        {
                            countErr++;
                            listErr.Add(new Utilities.ListItem(line.ToString(), dReader["OrderID"].ToString(), e.Message));
                            exist = true;
                        }

                        //check valid data
                        if (!exist)
                        {
                            try
                            {
                                OrderID = (dReader["OrderID"].ToString().Trim().Equals(string.Empty))
                                             ? "null"
                                             : "N'" + dReader["OrderID"].ToString().Trim() + "'";
                                ProductID = (dReader["ProductID"].ToString().Trim().Equals(string.Empty))
                                                ? "null"
                                                : "N'" + dReader["ProductID"].ToString().Trim() + "'";
                                Deadline = (dReader["Deadline"].ToString().Trim().Equals(string.Empty))
                                                ? "null"
                                                : "'" + DateTime.Parse(dReader["Deadline"].ToString().Trim()).ToString("yyyy/MM/dd") + "'";
                                Quantity = (dReader["Quantity"].ToString().Trim().Equals(string.Empty))
                                                 ? "null"
                                                 : dReader["Quantity"].ToString().Trim();
                                ExchangeRate = (dReader["ExchangeRate"].ToString().Trim().Equals(string.Empty))
                                            ? "null"
                                            : dReader["ExchangeRate"].ToString().Trim();
                                PurchaseID = (dReader["PurchaseID"].ToString().Trim().Equals(string.Empty))
                                             ? "null"
                                             : "N'" + dReader["PurchaseID"].ToString().Trim() + "'";
                                PGroupID = (dReader["PGroupID"].ToString().Trim().Equals(string.Empty))
                                                ? "null"
                                                : "N'" + dReader["PGroupID"].ToString().Trim() + "'";
                                Status = (dReader["Status"].ToString().Trim().Equals(string.Empty))
                                               ? "null"
                                               : "N'" + dReader["Status"].ToString().Trim() + "'";
                                Note = (dReader["Note"].ToString().Trim().Equals(string.Empty))
                                                 ? "null"
                                                 : "N'" + dReader["Note"].ToString().Trim() + "'";
                                ArrivedDate = (dReader["ArrivedDate"].ToString().Trim().Equals(string.Empty))
                                                ? "null"
                                                : "'" + DateTime.Parse(dReader["ArrivedDate"].ToString().Trim()).ToString("yyyy/MM/dd") + "'";
                                

                            }
                            catch (Exception ex)
                            {
                                exist = true;
                                listErr.Add(new Utilities.ListItem(line.ToString(),
                                                                   dReader["OrderID"].ToString(),
                                                                   ex.Message));
                            }
                        }

                        //check ProductID in [243_Product]?
                        if (!exist)
                        {

                            try
                            {
                                SqlCommand cmd_sql = myConnection.CreateCommand();
                                cmd_sql.CommandText = "SELECT * FROM [243_Product] WHERE [ProductID]=N'" +
                                                      dReader["ProductID"].ToString() + "'";
                                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                                if (!dataReader.Read())
                                {

                                    exist = true;
                                    countErr++;
                                    listErr.Add(new Utilities.ListItem(line.ToString(), dReader["OrderID"].ToString(),
                                                                       "Invalid ProductID"));
                                    //lineNo += line.ToString() + ", ";
                                }
                                else
                                {
                                    Price = (dataReader["Price"].ToString().Trim().Equals(string.Empty))
                                                ? "null"
                                                : dataReader["Price"].ToString().Trim();
                                }
                                dataReader.Close();
                                cmd_sql.Dispose();
                            }
                            catch (Exception ex)
                            {
                                exist = true;
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["OrderID"].ToString(),
                                                                   ex.Message));
                            }
                        }
                        //Insert to database
                        if (!exist)
                        {
                            try
                            {
                                string sql = "INSERT INTO [243_OrderInput] ([OrderID],[ProductID],[Deadline],[Quantity],[ExchangeRate],[PurchaseID]" +
                                             ",[PGroupID],[Status],[Note],[ArrivedDate],[Price]) " +
                                             "VALUES (" + OrderID + ", " + ProductID + ", " + Deadline + ","
                                         + Quantity + "," + ExchangeRate + "," + PurchaseID + "," + PGroupID + "," + Status + "," + Note + ","
                                         + ArrivedDate + "," + Price + ")";
                                SqlCommand cmd_sql = new SqlCommand(sql, myConnection);

                                cmd_sql.ExecuteNonQuery();
                                cmd_sql.Dispose();
                                countOk++;

                                //write Log
                                log.Table = LogConstant.Table.F2Order.OrderInput;
                                log.Task = LogConstant.Task.Import;
                                log.Description = "OrderID: " + OrderID + "; ProductID: " + ProductID;
                                log.WriteLog();

                            }
                            catch (Exception ex)
                            {
                                listErr.Add(new Utilities.ListItem(line.ToString(), dReader["OrderID"].ToString(), ex.Message));
                            }

                        }
                    }
                    myConnection.Close();
                    progressPanel1.Visible = false;
                    excelConnection.Close();
                    //MessageBox.Show(i + " records have been imported. \n" + countDup.ToString() + " record(s) duplicated (Lines: " + lineDup + ")\nLines have error OptionID: " + lineNo);
                    //LoadData();
                    Frm_ImportReport report = new Frm_ImportReport(countOk, listDup, listErr, "OrderInput", "OrderID");
                    report.StartPosition = FormStartPosition.CenterScreen;
                    report.Show();
                    report.Activate();
                }
                catch (Exception ex)
                {
                    if (excelConnection.State == ConnectionState.Open)
                    {
                        excelConnection.Close();
                    }
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    progressPanel1.Visible = false;
                    MessageBox.Show(ex.Message);
                }

            }
        }

        #endregion



    }
}
